package com.uottawa.library.controller;

import java.io.IOException;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.uottawa.library.domain.Title;
import com.uottawa.library.service.TitleService;
 
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name="/TitleServlet",  urlPatterns={"/addTitle.do", "/removeTitle.do", "/updateTitle.do", "/showTitle.do", "/displayTitle.do" })

public class TitleServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private TitleService titleService = new TitleService();
	
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        String isbn = request.getParameter("isbn");
        String name = request.getParameter("name");
        
        if(isbn.isEmpty() || name.isEmpty()) {
        	 request.setAttribute("error", "all fields are required");
        	 request.getRequestDispatcher("/title.jsp").forward(request, response);
        	 return;
        }
        String url = request.getServletPath();
        if(url.contains("add")) {
        	String result = titleService.addTitle(Integer.parseInt(isbn), name);
            request.setAttribute("result", result);
        } else if(url.contains("update")) {
        	String result = titleService.updateTitle(Integer.parseInt(isbn), name);
            request.setAttribute("result", result);
        }
       
        
    	request.getRequestDispatcher("/title.jsp").forward(request, response);

 
    }
    
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	
    	String url = request.getServletPath();
    	
    	if(url.contains("remove")) {
    		String isbn = request.getParameter("isbn");
    		if(isbn != null) {
    			String result = titleService.removeTitle(Integer.parseInt(isbn));
    			request.setAttribute("result", result);			
    		} else {
    			List<Title> titles = titleService.getAllTitles();
    			request.setAttribute("titles", titles);			
    		}
    	} else if(url.contains("update")){
    		List<Title> titles = titleService.getAllTitles();
			request.setAttribute("titles", titles);	
    	}
    	else if(url.contains("display")){
    		List<Title> titles = titleService.getAllTitles();
			request.setAttribute("titles", titles);	
    	}
    	request.getRequestDispatcher("/title.jsp").forward(request, response);

 
    }
    
    
    
}